<?php

namespace App\Observers;

use App\Models\Fang;
use Elasticsearch\ClientBuilder;
use Illuminate\Support\Facades\Log;

class FangObserver
{
    /**
     * Handle the Fang "created" event.
     *
     * @param \App\Models\Fang $fang
     * @return void
     */
    public function created(Fang $fang)
    {
        try {
            $hosts = [
                '127.0.0.1:9200',
            ];

            $client = ClientBuilder::create()
                ->setHosts($hosts)
                ->build();

            $params = [
                'index' => 'fang',
                'id' => $fang->id,
                'body' => $fang->toArray()
            ];

            $res = $client->index($params);
            if($res){
                Log::info($fang->id.'的房源数据同步成功');
            }
        } catch (\Exception $exception) {
            //如果同步失败，放到日志队列里
            $redis = new \Redis();
            $redis->rPush('fang_list',$fang->id);
        }
    }

    /**
     * Handle the Fang "updated" event.
     *
     * @param \App\Models\Fang $fang
     * @return void
     */
    public function updated(Fang $fang)
    {
        //
    }

    /**
     * Handle the Fang "deleted" event.
     *
     * @param \App\Models\Fang $fang
     * @return void
     */
    public function deleted(Fang $fang)
    {
        //
    }

    /**
     * Handle the Fang "restored" event.
     *
     * @param \App\Models\Fang $fang
     * @return void
     */
    public function restored(Fang $fang)
    {
        //
    }

    /**
     * Handle the Fang "force deleted" event.
     *
     * @param \App\Models\Fang $fang
     * @return void
     */
    public function forceDeleted(Fang $fang)
    {
        //
    }
}
